<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="ns" placeholder="请输入名称空间" style="width: 200px; margin-left: 10px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.name" placeholder="请输入cj控制器名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="名称" prop="name" min-width="120" />
      <el-table-column label="名称空间" prop="namespace" min-width="120" />
      <el-table-column label="镜像" prop="image" min-width="200" show-overflow-tooltip />
      <el-table-column label="调度规则" prop="schedule" min-width="140" />
      <el-table-column label="状态" prop="status" min-width="90">
        <template slot-scope="{row}">
          <el-tag :type="row.status==='active'?'success':'info'">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="启动命令" min-width="250" show-overflow-tooltip>
        <template slot-scope="{row}">
          <code>{{ row.command.join(' ') }}</code>
        </template>
      </el-table-column>
      <!-- 新增操作列 -->
      <el-table-column label="操作" min-width="180" align="center">
        <template slot-scope="{ row }">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            class="mr-2"
            @click="handleUpdate(row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 新增CronJob对话框 -->
    <el-dialog title="新增 CronJob" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" label-width="100px" style="width:600px;margin-left:50px;">
        <el-form-item label="资源名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="名称空间" prop="namespace">
          <el-input v-model="temp.namespace" />
        </el-form-item>
        <el-form-item label="容器名称" prop="containername">
          <el-input v-model="temp.containername" />
        </el-form-item>
        <el-form-item label="定时规则" prop="schedule">
          <el-input v-model="temp.schedule" />
        </el-form-item>
        <el-form-item label="镜像" prop="image">
          <el-input v-model="temp.image" />
        </el-form-item>
        <el-form-item label="启动命令">
          <div v-for="(item, idx) in cmdInputs" :key="idx" style="margin-bottom:4px;">
            <el-input
              v-model="cmdInputs[idx]"
              placeholder="输入执行命令"
              style="width:200px"
            />
            <el-button
              v-if="idx === 0"
              type="text"
              icon="el-icon-plus"
              @click="addLine"
            >新增
            </el-button>
            <el-button
              v-else
              type="text"
              icon="el-icon-minus"
              @click="delLine(idx)"
            >删除
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible=false">Cancel</el-button>
        <el-button type="primary" @click="createData">Confirm</el-button>
      </div>
    </el-dialog>

    <!-- 修改CronJob对话框 -->
    <el-dialog title="修改 CronJob" :visible.sync="dialogUpdateVisible">
      <el-form ref="updateForm" :model="updateTemp" label-width="100px" style="width:600px;margin-left:50px;">
        <el-form-item label="资源名称" prop="name" disabled>
          <el-input v-model="updateTemp.name" disabled />
        </el-form-item>
        <el-form-item label="名称空间" prop="namespace" disabled>
          <el-input v-model="updateTemp.namespace" disabled />
        </el-form-item>
        <el-form-item label="镜像" prop="image">
          <el-input v-model="updateTemp.image" placeholder="可选，不修改请留空" />
        </el-form-item>
        <el-form-item label="定时规则" prop="schedule">
          <el-input v-model="updateTemp.schedule" placeholder="可选，不修改请留空" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUpdateVisible=false">取消</el-button>
        <el-button type="primary" @click="updateData">确认</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCronJobList, createCronJob, deleteCronJob, updateCronJob } from '@/api/k8sCronJob'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      ns: 'default',
      list: [],
      total: 0,
      listLoading: false,
      listQuery: { page: 1, limit: 20, name: undefined, sort: '+id' },
      temp: { name: '', namespace: '', containername: '', schedule: '', image: '' },
      cmdInputs: [''],
      dialogFormVisible: false,
      dialogUpdateVisible: false,
      updateTemp: { name: '', namespace: '', image: '', schedule: '' },
      dialogStatus: '',
      textMap: { update: 'Edit', create: 'Create' },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /* 动态命令行 */
    addLine() {
      this.cmdInputs.push('')
    },
    delLine(idx) {
      this.cmdInputs.splice(idx, 1)
    },
    /* 列表 - 使用async/await重构，增强错误处理 */
    async getList() {
      this.listLoading = true
      try {
        // 检查API函数是否存在
        if (typeof getCronJobList !== 'function') {
          throw new Error('getCronJobList 函数未定义，请检查API导入')
        }
        // 注意：根据实际API定义调整参数顺序
        const res = await getCronJobList(this.listQuery, this.ns)
        this.list = res?.items || []
        this.total = this.list.length
      } catch (err) {
        console.error('获取列表失败:', err)
        this.$message.error('加载数据失败: ' + (err.message || '未知错误'))
        this.list = []
        this.total = 0
      } finally {
        this.listLoading = false // 无论成功失败都关闭加载状态
      }
    },
    handleFilter() {
      if (!this.ns || this.ns.trim() === '') {
        this.$message.warning('请输入名称空间')
        return
      }
      this.listQuery.page = 1
      this.getList()
    },
    sortChange({ prop, order }) {
      const sort = order === 'ascending' ? '+' : '-'
      this.listQuery.sort = sort + prop
      this.getList()
    },

    /* 新增 */
    handleCreate() {
      this.temp = { name: '', namespace: '', containername: '', schedule: '', image: '' }
      this.cmdInputs = ['']
      this.dialogFormVisible = true
    },
    createData() {
      const payload = {
        name: this.temp.name,
        namespace: this.temp.namespace,
        containername: this.temp.containername,
        schedule: this.temp.schedule,
        image: this.temp.image,
        command: this.cmdInputs.filter(v => v.trim())
      }
      createCronJob(payload)
        .then(() => {
          this.$message.success('创建成功')
          this.dialogFormVisible = false
          this.ns = payload.namespace
          this.cmdInputs = ['']
          this.getList()
        })
        .catch(err => {
          this.$message.error(err.message || '创建失败')
        })
    },

    /* 编辑操作 */
    /* 编辑操作 */
    handleUpdate(row) {
      // 存储完整的行数据，用于更新
      this.updateRowData = { ...row }

      // 初始化修改表单数据
      this.updateTemp = {
        name: row.name,
        namespace: row.namespace,
        image: row.image || '',
        schedule: row.schedule || ''
      }
      this.dialogUpdateVisible = true
    },

    /* 执行修改 - 直连后端版本 */
    updateData() {
    // 验证至少需要修改一个字段
      if (!this.updateTemp.image && !this.updateTemp.schedule) {
        this.$message.warning('请至少修改一个字段（镜像或定时规则）')
        return
      }

      // 构建完整的更新请求体
      const payload = {
        name: this.updateRowData.name,
        namespace: this.updateRowData.namespace,
        containername: this.updateRowData.containername || '',
        schedule: this.updateTemp.schedule || this.updateRowData.schedule,
        image: this.updateTemp.image || this.updateRowData.image,
        command: this.updateRowData.command || []
      }

      console.log('🔄 发送更新请求:', payload)

      updateCronJob(payload)
        .then((response) => {
        // 判断返回的code是否为20000
          if (response.code === 20000) {
            this.$message.success('修改成功')
            this.dialogUpdateVisible = false
            this.getList()
          } else {
            throw new Error(response.message || '修改失败')
          }
        })
        .catch(error => {
          console.error('更新失败:', error)
          this.$message.error('修改失败: ' + error.message)
        })
    },
    /* 删除操作 */
    // 在你的 Vue 组件中
    handleDelete(row) {
      this.$confirm(`确定要删除cj "${row.name}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        deleteCronJob(row.namespace, row.name)
          .then((response) => {
            // 判断返回的code是否为20000
            if (response.code === 20000) {
              this.getList()
              this.$message.success(`cj ${row.name} 删除成功`)
            } else {
              // 如果code不是20000，视为失败
              throw new Error(response.message || '删除失败')
            }
          })
          .catch(error => {
            console.error('删除cj失败:', error)
            this.$message.error('删除cj失败: ' + error.message)
          })
          .finally(() => {
            this.listLoading = false
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }

  }
}
</script>
